package com.zhz.order.config;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @program: idempotent_redis
 * @description:
 * @author: zhanghz001
 * @create: 2021-03-16 11:22
 **/
@Component
public class RedissonLock {
    @Autowired(required = false)
    RedissonClient redissonClient;
    
    /**
     * 加锁
     *
     * @param lockKey
     * @return
     */
    public boolean addLock(String lockKey) {
        try {
            if (redissonClient == null) {
                System.out.println("redissonClient is null");
                return false;
            }
            RLock lock = redissonClient.getLock(lockKey);
            boolean b = true;
            //设置的是过期时间,时间过短,会导致提前释放造成死锁
            // lock.lock(10, TimeUnit.SECONDS);
            
            //不需要设置过期时间了,因为过期时间会自动续
            // 这个设置的是等待时间,如果设置的短了,就不等待了
            b = lock.tryLock(1000, TimeUnit.SECONDS);
            
            System.out.println(Thread.currentThread().getName() + ": 获取到锁" + b);
            
            //加锁成功
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            
        }
    }
    
    public boolean realease(String lockKey) {
        try {
            if (redissonClient == null) {
                System.out.println("redissonClient is null");
                return false;
            }
            
            //获取到锁
            RLock lock = redissonClient.getLock(lockKey);
            
            //释放锁
            lock.unlock();
            
            System.out.println(Thread.currentThread().getName() + ": 释放锁");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            
        }
    }
}
